'''
@author: zhangkai
@license: (C) Copyright 2017-2023
@contact: jeffcobile@gmail.com
@Software : PyCharm
@file: register.py
@time: 2020-05-29 11:14:51
@desc: 
'''
class Registry(object):
    def __init__(self, name):
        self._name = name
        self._obj_map_ = {}

    def get(self, name):
        ret = self._obj_map_.get(name)
        if ret is None:
            raise KeyError("No object named '{}' found in '{}' registry!".format(name, self._name))

        return ret

    def _do_register(self, name, obj):
        assert (
            name not in self._obj_map_
        ), "An object named '{}' was already registered in '{}' registry!".format(name, self._name)
        self._obj_map_[name] = obj

    def register(self, obj=None, name=None):
        """
        Register the given object under the the name `obj.__name__`.
        Can be used as either a decorator or not. See docstring of this class for usage.
        """
        if obj is None:
            # used as a decorator
            def deco(func_or_class, name=name):
                if name is None:
                    name = func_or_class.__name__
                self._do_register(name, func_or_class)
                return func_or_class

            return deco

        # used as a function call
        if name is None:
            name = obj.__name__
        self._do_register(name, obj)